<template>
  <view class="certificate">
    <van-nav-bar title="实名认证" left-arrow fixed placeholder z-index="88"
      custom-style="--nav-bar-arrow-size: 40rpx;--nav-bar-icon-color: #000;" @click-left="onClickLeft" />
    <template v-if="!black_Get(info, '_raw.isCertificate', 0)">
      <view class="certificate__tip">
        请拍摄并上传您的身份证照片
      </view>
      <view class="certificate__Id-card">
        <view class="certificate__Id-card--picture">
          <view>
            <view @tap.stop="clickUpload(0, IDcardPicture[0])">
              <view v-if="!!IDcardPicture[0]">
                <image :src="IDcardPicture[0]"></image>
                <van-icon name="cross" color="#fff" size="44rpx" @tap.stop="deleteIDcardPicture(0)" />
              </view>
              <view v-else>
                <image :src="'member/ID-card-front.png' | prefixOssUrl"></image>
                <image class="camera-icon" mode="aspectFit" :src="'member/camera-icon.png' | prefixOssUrl"></image>
              </view>
            </view>
            <view>请上传身份证正面</view>
          </view>
          <view>
            <view @tap.stop="clickUpload(1, IDcardPicture[1])">
              <view v-if="!!IDcardPicture[1]">
                <image :src="IDcardPicture[1]"></image>
                <van-icon name="cross" color="#fff" size="44rpx" @tap.stop="deleteIDcardPicture(1)" />
              </view>
              <view v-else>
                <image :src="'member/ID-card-back.png' | prefixOssUrl"></image>
                <image class="camera-icon" mode="aspectFit" :src="'member/camera-icon.png' | prefixOssUrl"></image>
              </view>
            </view>
            <view>请上传身份证反面</view>
          </view>
        </view>

        <van-divider contentPosition="center"
          customStyle="--divider-text-color:#999;--divider-font-size: 30rpx;--divider-margin:28rpx 0;font-weight: 400;">
          身份证拍摄要求</van-divider>
        <view class="certificate__Id-card--templet">
          <view class="title">
            <view>拍摄时请确保身份证</view>
            <view>边框完整，字体清晰，亮度均匀</view>
          </view>
          <view class="content">
            <view>
              <image :src="'member/ID-card-eligible.png' | prefixOssUrl"></image>
              <van-icon name="checked" size="30rpx" color="#52c41a" />
              <view>标准样式</view>
            </view>
            <view>
              <image :src="'member/ID-card-unqualified.png' | prefixOssUrl"></image>
              <van-icon name="clear" size="30rpx" color="#f99800" />
              <view>拍摄不完整</view>
            </view>
            <view>
              <image :src="'member/ID-card-blurry.png' | prefixOssUrl"></image>
              <van-icon name="clear" size="30rpx" color="#f99800" />
              <view>拍摄模糊</view>
            </view>
            <view>
              <image :src="'member/ID-card-over-exposure.png' | prefixOssUrl"></image>
              <van-icon name="clear" size="30rpx" color="#f99800" />
              <view>闪光遮挡</view>
            </view>
          </view>
        </view>
      </view>
    </template>
    <template v-else>
      <view class="certificate__Id-card--picture">
        <image mode="aspectFit" v-for="(item, index) in JSON.parse(black_Get(this.info, '_raw.idCardJson', '[]'))"
          :key="index" :src="item.url" @tap="clickUpload(null, item.url)"></image>
      </view>
    </template>
    <van-cell title="姓名：" :value="IDCard.IDCardName || ''" />
    <van-cell title="性别：" :value="IDCard.IDCardSex || ''" />
    <van-cell title="出生日期：" :value="(IDCard.IDCardBirth || '').replace(/^(.{4})(.*)(.{2})/, '$1/$2/$3')" />
    <van-cell title="身份证号：" :value="IDCard.IDCardNumber || ''" />
    <van-cell title="有效期限："
      :value="(IDCard.IdCardExpire || '-').split('-')[1].replace(/^(.{4})(.*)(.{2})/, '$1年$2月$3日')" />
    <van-cell title="证件地址：" :value="IDCard.IDCardAddress || ''" :border="false" />
    <view class="certificate__button" v-if="!black_Get(info, '_raw.isCertificate', 0)">
      <button :style="!goCertification && 'opacity: .5;'" @tap="submit">
        去认证
      </button>
    </view>
    <view class="certificate__button--cancel" v-else>
      <button @tap="cancelCertificate">
        取消绑定认证
      </button>
    </view>
    <van-popup :show="popup.show" position="right" custom-style="width: 100%;height: 100%">
      <view class="bind-phone">
        <van-nav-bar title="实名认证" left-arrow placeholder
          custom-style="--nav-bar-arrow-size: 40rpx;--nav-bar-icon-color: #000;" @click-left="popup.show = false" />
        <view class="bind-phone__content">
          <view class="bind-phone__content--text">
            <view>您当前绑定手机号为：</view>
            <view class="cell-phone">{{ black_Get(info, 'mobile').replace(/^(.{3})(.*)(.{4})/, '$1 $2 $3') }}</view>
            <view>请验证身份</view>
          </view>
          <view class="bind-phone__content--verification-code">
            <view>
              <icon class="iconfont icon">&#xe634;</icon>
              <input type="number" maxlength="10" :value="popup.inputVerifyCodeValue" placeholder="请输入验证码"
                @input="popup.input" />
              <van-icon v-show="popup.inputVerifyCodeValue" name="clear" color="#d5d5d5" size="40rpx"
                @click="popup.deleteVerifyCode" />
            </view>
            <view @tap="popup.clickSend">
              <view class="get-code" v-if="!popup.getCode">获取验证码</view>
              <view class="re-get-code" v-else-if="popup.resend">重新发送</view>
              <view class="countdown-clock" v-else>{{ `0${Math.max(countdownClock, 0)}`.slice(-2) }}S</view>
            </view>
          </view>
          <view v-show="popup.anError">
            *验证码错误，请重新发送或输入。
          </view>
          <view class="bind-phone__content--btn"
            :style="popup.inputVerifyCodeValue !== popup.verifyCode && 'opacity: .5;'"
            @tap="popup.goPage.call(this, popup.inputVerifyCodeValue === popup.verifyCode)">提交认证</view>
          <view @tap="nav('/subpackage/member/pages/account/mobile/index?isChangePhone=1')">
            切换修改手机号
            <van-icon name="arrow" color="#999" size="36rpx" />
          </view>
        </view>
      </view>
    </van-popup>
  </view>
</template>

<script>
  import {
    mapActions,
    mapState
  } from 'vuex';
  import {
    model
  } from '@/model';
  import EventBus from "@/event/index";
  const {
    Request
  } = model;
  const {
    Member,
  } = model.collection;
  export default {
    onLoad() {
      this.popup.mobile = this.black_Get(this.info, 'mobile');
      if (this.black_Get(this.info, '_raw.isCertificate', 0)) {
        Object.assign(this.IDCard, {
          IDCardName: this.black_Get(this.info, '_raw.realName', ''),
          IDCardSex: ['男', '女'][this.black_Get(this.info, '_raw.sex', 0) - 1],
          IDCardBirth: this.$dayjs(this.black_Get(this.info, '_raw.birthday', '')).format('YYYYMMDD'),
          IDCardNumber: this.black_Get(this.info, '_raw.idCardNumber', ''),
          IdCardExpire: this.black_Get(this.info, '_raw.idCardExpire', ''),
          IDCardAddress: this.black_Get(this.info, '_raw.liveAddress', '')
        })
      }
      EventBus.$on("isChangePhone", (value) => {
        this.isChangePhone = value;
        this.popup.show = !value;
      });
    },
    data() {
      return {
        request: new Request(),
        popup: {
          show: false,
          anError: false,
          verifyCode: NaN,
          mobile: '',
          inputVerifyCodeValue: '',
          now: 0,
          getCode: false,
          resend: false,
          clickSend() {
            if (!this.popup.getCode) {
              this.popup.sendVerifyCode.call(this);
              this.popup.getCode = true;
              this.popup.now = Date.now() + 59000;
              return
            }

            if (this.countdownClock < 0) {
              this.popup.sendVerifyCode.call(this);
              this.popup.resend = false;
              this.popup.now = Date.now() + 59000;
            }
          },
          sendVerifyCode() {
            this.request.do('open', 'verify', 'mobileCode', {
              params: {
                app: 'common',
                bizType: 1,
                mobile: this.black_Get(this.info, 'mobile')
              },
              data: {}
            }).then((res) => {
              const {
                status,
                data
              } = res;
              if (status) {
                this.toast('发送验证码成功!');
                this.popup.verifyCode = data;
              } else {
                this.toast('发送失败')
              }
            });
          },
          input(e) {
            const {
              value
            } = e.detail;
            if (this.popup.verifyCode && value.length >= this.popup.verifyCode.length) {
              this.popup.anError = value !== this.popup.verifyCode;
            }
            this.popup.inputVerifyCodeValue = value;
          },
          deleteVerifyCode() {
            this.popup.inputVerifyCodeValue = '';
          },
          goPage(bool) {
            if (bool) {
              let form = this.getParameters;
              Object.assign(form.params, {
                isPreView: 0,
                isRequireMobile: Number(!this.isChangePhone),
                mobile: this.popup.mobile,
                verifyCode: this.popup.verifyCode || '',
              })
              form.data = this.aliyuncsIDcardTemporaryPicture;
              this.doCertificate(form, () => {
                this.red("/subpackage/member/pages/certificate/success");
              })
            }
          },
        },
        onClickLeft() {
          uni.navigateBack({
            fail: () => {
              uni.showModal({
                cancelText: '取消',
                confirmColor: "#DB187C",
                confirmText: '前往认证',
                title: '提示',
                content: '您还没有完成实名认证，请前往认证!',
                success: (res) => {
                  if (res.confirm) {
                    uni.reLaunch({
                      url: '/subpackage/member/pages/certificate/index'
                    });
                    return
                  }
                  this.logout().then(() => {
                    uni.reLaunch({
                      url: '/pages/login/index?certificate=1'
                    })
                  });
                }
              })
            }
          });
        },
        IDcardPicture: [],
        aliyuncsIDcardTemporaryPicture: [],
        isChangePhone: false,
        IDCard: {},
        goCertification: false,
        deleteIDcardPicture(index) {
          this.$set(this.IDcardPicture, index, null)
        },
        clickUpload(index, src) {
          if (src) {
            wx.previewImage({
              urls: [src]
            })
            return
          }
          uni.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: ['album', 'camera'],
            sizeType: ['original', 'compressed'],
            success: (res) => {
              this.$set(this.IDcardPicture, index, res.tempFiles[0].tempFilePath)
            }
          })
        },
        async cancelCertificate() {
          const modal = await uni.showModal({
            cancelColor: "#999999",
            cancelText: '我再想想',
            confirmColor: "#DB187C",
            confirmText: '确认取消',
            title: '是否取消实名认证？',
            content: '取消后，您将无法下单。',
          });
          if (!modal[1].confirm) {
            return
          }
          const res = await Member.sendApi('cancelCertificate');
          if (res.code !== 2000) {
            return
          }

          EventBus.$emit("cancelCertificate", true);
          this.getUserInfo();
          this.back();
        },
        submit() {
          if (this.isChangePhone) {
            this.popup.goPage.call(this, true);
          } else {
            this.popup.show = this.goCertification
          }
        }
      }
    },
    computed: {
      ...mapState(["now"]),
      ...mapState('user', ['info']),
      countdownClock() {
        let time = this.popup.now - this.now;

        if (this.popup.getCode && time < 0) {
          this.popup.resend = true;
        }
        time = (~~(time / 1000)) % 60;

        return time
      },
      getParameters() {
        return {
          params: {
            isPreView: 1,
            isRequireMobile: 0,
            mobile: '',
            verifyCode: '',
          },
          data: this.IDcardPicture
        }
      }
    },
    watch: {
      getParameters: {
        handler: function (e) {
          if (!e.data[0] || !e.data[1]) {
            this.goCertification = false;
            return
          }

          let json = e.data.map(item => {
            return {
              url: item
            }
          })
          let ossRequestArr = [];
          for (let item of json) {
            ossRequestArr.push(this.ossRequest(item));
          }
          Promise.all(ossRequestArr).then(res => {
            e.data = ['front', 'back'].map((item, index) => {
              return {
                type: item,
                url: `https:${res[index].data.url}`
              }
            })
            this.aliyuncsIDcardTemporaryPicture = e.data;
            this.doCertificate(e);
          })
        },
        deep: true
      }
    },
    methods: {
      ...mapActions('user', ['getUserInfo', 'logout']),
      ossRequest(file) {
        return this.request
          .do("open", "oss", "authorize", {
            params: {},
            data: {},
          })
          .then((res) => {
            if (res.status) {
              return this.upload(res.data, file);
            }
          })
          .then((res) => {
            if (res.status) {
              return res;
            } else {
              throw new Error();
            }
          })
          .catch(() => {
            this.toast("上传图片失败");
          });
      },
      doCertificate(parameters, fn) {
        Member.sendApi('doCertificate', parameters).then(res => {
          if (res.code === 6404) {
            this.showTipModal('请上传有效身份证！');
            return
          }

          if (res.code === 5400) {
            this.showTipModal(res.message);
            return
          }

          if(res.code === 5405){
            this.showTipModal('该身份证已被使用！');
            return
          }

          if (res.code !== 2000) {
            return
          }
          if (fn) {
            fn();
            return
          }
          this.goCertification = true;
          Object.assign(this.IDCard, res.data);
          EventBus.IDcardTemporaryPicture = this.IDcardPicture;
        }).catch(() => {
          this.goCertification = false;
          this.IDCard = {};
          uni.showModal({
            showCancel: false,
            confirmColor: "#DB187C",
            title: '提示',
            content: '请规范上传身份证照片。',
          });
        })
      },
      showTipModal(content) {
        uni.showModal({
          showCancel: false,
          confirmColor: "#DB187C",
          title: '提示',
          content
        });
      }
    }
  };
</script>
<style lang="less" scoped>
  .certificate {
    padding-bottom: 148rpx;
    min-height: 100vh;
    background: #F7F7F7;

    &__tip {
      padding-left: 30rpx;
      height: 100rpx;
      font-size: 34rpx;
      font-weight: bold;
      color: #333333;
      line-height: 100rpx;
    }

    &__Id-card {
      margin-bottom: 30rpx;
      padding: 40rpx 30rpx 56rpx;
      background-color: #fff;
      box-sizing: border-box;

      &--picture {
        display: flex;
        justify-content: space-between;
        width: 100%;
        padding: 0 14rpx;
        box-sizing: border-box;

        >image {
          display: block;
          margin: 40rpx 26rpx;
          width: 314rpx;
          height: 200rpx;
          border-radius: 15rpx;
        }

        >view {
          >view:first-child {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 309rpx;
            height: 230rpx;
            background:
              linear-gradient(#E1E1E1, #E1E1E1) left top,
              linear-gradient(#E1E1E1, #E1E1E1) left top,
              linear-gradient(#E1E1E1, #E1E1E1) right top,
              linear-gradient(#E1E1E1, #E1E1E1) right top,
              linear-gradient(#E1E1E1, #E1E1E1) left bottom,
              linear-gradient(#E1E1E1, #E1E1E1) left bottom,
              linear-gradient(#E1E1E1, #E1E1E1) right bottom,
              linear-gradient(#E1E1E1, #E1E1E1) right bottom;
            background-repeat: no-repeat;
            background-size: 38rpx 6rpx, 6rpx 38rpx;

            >view {
              position: relative;

              image {
                width: 258rpx;
                height: 165rpx;
                border-radius: 10rpx;
              }

              .camera-icon {
                position: absolute;
                left: 0;
              }

              /deep/ .van-icon {
                position: absolute;
                top: 0;
                right: 0;
                padding: 6rpx;
                background-color: rgba(0, 0, 0, 0.7);
                border-radius: 0 10rpx 0 10rpx;
              }
            }
          }

          >view:last-child {
            margin-top: 20rpx;
            font-size: 24rpx;
            font-weight: bold;
            color: #333333;
            line-height: 1;
            text-align: center;
          }
        }
      }

      &--templet {
        .title {
          display: flex;
          justify-content: space-between;
          font-size: 28rpx;
          color: #333;

          >view:last-child {
            color: #ff8500;
          }
        }

        .content {
          display: flex;
          justify-content: space-between;
          margin-top: 30rpx;

          >view {
            display: flex;
            align-items: center;
            flex-direction: column;
            font-size: 24rpx;
            color: #333;

            image {
              margin-bottom: 14rpx;
              width: 148rpx;
              height: 98rpx;
            }

            >view {
              margin-top: 14rpx;
              line-height: 1;
            }
          }
        }
      }
    }

    /deep/.van-cell {
      &__value {
        flex-grow: 3;
        font-size: 32rpx;
        color: #333;
        white-space: pre-wrap;
        word-break: break-all;
      }
    }

    &__button,
    &__button--cancel {
      position: fixed;
      z-index: 10;
      bottom: 0;
      display: flex;
      align-items: center;
      padding: 0 30rpx;
      width: 100%;
      height: 148rpx;
      box-shadow: 0 0 11rpx 0 rgba(8, 1, 3, 0.1);
      box-sizing: border-box;
      background-color: #fff;

      >button {
        width: 100%;
        height: 90rpx;
        font-size: 34rpx;
        font-weight: bold;
        color: #fff;
        background-color: #db187c;
        text-align: center;
        line-height: 90rpx;
        border-radius: 6rpx;
      }
    }

    &__button--cancel {
      background-color: transparent;
      box-shadow: none;

      >button {
        font-weight: 500;
        color: #DB187C;
        background-color: #FFE5F3;

        &::after {
          border: none;
        }
      }
    }

    .bind-phone {
      display: flex;
      flex-direction: column;
      height: 100%;

      &__content {
        position: relative;
        flex-grow: 1;

        &--text {
          display: flex;
          align-items: center;
          flex-direction: column;
          margin: 40rpx 0 60rpx;

          >view {
            line-height: 1;
          }

          .cell-phone {
            margin: 20rpx 0;
            font-size: 36rpx;
            font-weight: bold;
          }

          >view:first-child {
            font-size: 34rpx;
            color: #333;

          }

          >view:last-child {
            font-size: 30rpx;
            color: #999;

          }
        }

        &--verification-code {
          display: flex;
          justify-content: space-between;
          align-items: initial;
          margin: 0 30rpx;
          height: 120rpx;
          background: #F7F7F7;

          >view:first-child {
            position: relative;
            display: flex;
            align-items: center;
            flex-shrink: 0;
            padding-left: 26rpx;
            width: 498rpx;
            font-size: 30rpx;
            color: #999;
            box-sizing: border-box;

            .icon {
              margin-top: -5rpx;
              font-size: 45rpx;
            }

            input {
              padding: 0 58rpx 0 18rpx;
              height: 100%;
              color: #333;
              box-sizing: border-box;
            }

            /deep/ .van-icon {
              position: absolute;
              top: 50%;
              right: 18rpx;
              z-index: 10;
              transform: translateY(-50%);

              &::after {
                content: '';
                position: absolute;
                top: -50%;
                left: -50%;
                width: 200%;
                height: 200%;
              }
            }
          }

          >view:last-child {
            display: flex;
            align-items: center;
            width: 100%;

            .get-code,
            .re-get-code,
            .countdown-clock {
              position: relative;
              width: 100%;
              font-size: 26rpx;
              font-weight: bold;
              color: #DB187C;
              text-align: center;

              &::before {
                content: '';
                position: absolute;
                left: 0;
                height: 100%;
                width: 1rpx;
                background: #EAEAEA;
              }
            }

            .re-get-code {
              font-weight: 500;
              color: #235CFF;
            }

            .countdown-clock {
              font-size: 30rpx;
            }
          }
        }

        &--verification-code+view {
          margin: 18rpx 0 0 30rpx;
          font-size: 24rpx;
          font-weight: bold;
          color: #FF486A;
          line-height: 1;
        }

        &--btn,
        &--btn+view {
          position: absolute;
          bottom: 190rpx;
          display: flex;
          justify-content: center;
          align-items: center;
          width: calc(100% - 150rpx);
          margin: 0 75rpx;
          height: 90rpx;
          font-size: 34rpx;
          color: #fff;
          background: #db187c;
          border-radius: 6rpx;
        }

        &--btn+view {
          bottom: 80rpx;
          align-items: center;
          font-size: 32rpx;
          color: #666;
          background: transparent;

          /deep/ .van-icon {
            margin-top: 6rpx;
          }
        }
      }
    }
  }
</style>